using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
using TMPro;
using System.Collections;
using UnityEngine.SceneManagement;

public class RewardPageUI : MonoBehaviour
{
    [Header("UI引用")]
    public GameObject battlePage;
    public GameObject rewardPage;
    public Transform cardSlotsParent; // 包含三个slot的父对象
    public TMP_Text selectedNumberText;
    public TMP_Text titleText;
    public GameObject confirmButton; // 改为GameObject引用

    [Header("卡牌预制体")]
    public GameObject rewardCardPrefab;

    private List<RewardCardView> rewardCardViews = new List<RewardCardView>();
    private List<Transform> cardSlots = new List<Transform>();
    private List<Card> currentRewardCards = new List<Card>();
    private int maxSelectedCard = 1;
    private int currentSelectedCount = 0;
    private RewardSelection currentSelection = new RewardSelection();
    private BattleResult currentResult = new BattleResult();

    void Awake()
    {
        Debug.Log($"RewardPageUI Awake 被调用，实例ID: {GetInstanceID()}");
        // 如果没有手动设置，尝试自动查找
        if (cardSlotsParent == null)
        {
            FindCardSlotsParent();
        }

        InitializeSlots();
        InitializeConfirmButton();
    }

    /// <summary>
    /// 自动查找卡牌槽位的父对象
    /// </summary>
    private void FindCardSlotsParent()
    {
        // 方法1：通过名称查找
        cardSlotsParent = transform.Find("RewardArea");
        if (cardSlotsParent == null)
        {
            // 方法2：查找包含Slot的对象
            Transform rewardArea = transform.Find("RewardArea");
            if (rewardArea != null)
            {
                cardSlotsParent = rewardArea;
            }
            else
            {
                // 方法3：查找包含Slot1, Slot2, Slot3的父对象
                Transform slot1 = transform.Find("Slot1");
                if (slot1 != null && slot1.parent != null)
                {
                    cardSlotsParent = slot1.parent;
                }
                else
                {
                    Debug.LogError("无法自动找到 cardSlotsParent，请在Inspector中手动设置");
                }
            }
        }

        if (cardSlotsParent != null)
        {
            Debug.Log($"自动找到 cardSlotsParent: {cardSlotsParent.name}");
        }
    }


    private void InitializeSlots()
    {
        rewardCardViews.Clear();
        cardSlots.Clear();

        // 获取所有slot并添加点击处理器
        for (int i = 0; i < cardSlotsParent.childCount; i++)
        {
            Transform slot = cardSlotsParent.GetChild(i);
            cardSlots.Add(slot);

            // 确保slot有BoxCollider
            BoxCollider boxCollider = slot.GetComponent<BoxCollider>();
            if (boxCollider == null)
            {
                boxCollider = slot.gameObject.AddComponent<BoxCollider>();
                // 设置合适的碰撞器大小
                boxCollider.size = new Vector3(2f, 3f, 0.1f);
            }

            // 添加SlotClickHandler组件
            SlotClickHandler clickHandler = slot.GetComponent<SlotClickHandler>();
            if (clickHandler == null)
            {
                clickHandler = slot.gameObject.AddComponent<SlotClickHandler>();
            }
            clickHandler.Initialize(this, i);
        }

        UpdateSelectedNumberText();

        Debug.Log("InitializeSlots finished");
    }

    private void InitializeConfirmButton()
    {
        if (confirmButton != null)
        {
            // 确保确认按钮有BoxCollider
            BoxCollider boxCollider = confirmButton.GetComponent<BoxCollider>();
            if (boxCollider == null)
            {
                boxCollider = confirmButton.AddComponent<BoxCollider>();
                boxCollider.size = new Vector3(2f, 1f, 0.1f);
            }

            // 添加ConfirmButtonClickHandler组件
            ConfirmButtonClickHandler clickHandler = confirmButton.GetComponent<ConfirmButtonClickHandler>();
            if (clickHandler == null)
            {
                clickHandler = confirmButton.AddComponent<ConfirmButtonClickHandler>();
            }
            clickHandler.Initialize(this);
        }

        Debug.Log("InitializeConfirmButton finished");
    }

    private void OnEnable()
    {
        Debug.Log($"- RewardPageUI 实例是否为null: {this == null}");

        // 注册事件
        ResultManager.OnShowBattleResult += ShowBattleResult;
        ResultManager.OnShowCardReward += ShowCardReward;

        Debug.Log("事件注册完成:");
        Debug.Log($"- ShowBattleResult 方法已注册");
        Debug.Log($"- ShowCardReward 方法已注册");

        ResetSelection();
    }

    private void OnDisable()
    {
        // 注销事件
        ResultManager.OnShowBattleResult -= ShowBattleResult;
        ResultManager.OnShowCardReward -= ShowCardReward;
    }

    private void ShowBattleResult(BattleResult result)
    {
        currentResult = result;
        Debug.Log($"result已赋值，当前战斗胜利:{currentResult.isVictory}");
        ShowTitleText();
    }

    private void ShowTitleText()
    {
        if (currentResult.isVictory)
        {
            titleText.text = "战斗胜利！";
        }
        else
        {
            titleText.text = "战斗失败";
        }
    }

    private void ShowCardReward(List<Card> rewardCards)
    {
        if(currentRewardCards.Count != 0)
        {
            currentRewardCards.Clear();
        }
        currentRewardCards = rewardCards;
        DisplayRewardCards(rewardCards);
        ResetSelection();

        // 更新按钮和Slot的状态
        UpdateConfirmButtonAndSlotsState();
    }

    /// <summary>
    /// 更新确认按钮和Slot的状态
    /// </summary>
    private void UpdateConfirmButtonAndSlotsState()
    {
        // 更新确认按钮状态
        if (confirmButton != null)
        {
            ConfirmButtonClickHandler buttonHandler = confirmButton.GetComponent<ConfirmButtonClickHandler>();
            if (buttonHandler != null)
            {
                // 战斗失败且没有奖励卡牌时按钮可点击，否则根据选择状态决定
                bool canClickDirectly = CanConfirmButtonClickDirectly();
                buttonHandler.SetInteractable(canClickDirectly || currentSelectedCount > 0);
            }
        }

        // 更新Slot状态
        bool slotsDisabled = ShouldSlotsBeDisabled();
        for (int i = 0; i < cardSlots.Count; i++)
        {
            SlotClickHandler slotHandler = cardSlots[i].GetComponent<SlotClickHandler>();
            if (slotHandler != null)
            {
                slotHandler.SetEnabled(!slotsDisabled);
            }
        }
    }

    private void DisplayRewardCards(List<Card> rewardCards)
    {
        Debug.Log("=== DisplayRewardCards 开始 ===");
        Debug.Log($"- 要显示的卡牌数量: {rewardCards?.Count ?? 0}");
        Debug.Log($"- 可用槽位数量: {cardSlots?.Count ?? 0}");

        // 清空现有的卡牌显示
        ClearRewardCards();

        // 为每个奖励卡牌创建UI
        for (int i = 0; i < Mathf.Min(rewardCards.Count, cardSlots.Count); i++)
        {
            if (rewardCards[i] != null && rewardCardPrefab != null)
            {
                Debug.Log($"- 为卡牌 {i} 创建UI: {rewardCards[i].name}");

                // 在slot中实例化卡牌预制体
                GameObject cardInstance = Instantiate(rewardCardPrefab, cardSlots[i]);
                cardInstance.transform.localPosition = Vector3.zero;
                cardInstance.transform.localRotation = Quaternion.identity;

                RewardCardView cardView = cardInstance.GetComponent<RewardCardView>();

                if (cardView != null)
                {
                    cardView.Initialize(rewardCards[i]);
                    rewardCardViews.Add(cardView);
                    Debug.Log($"- 卡牌 {i} UI 创建成功");
                }
                else
                {
                    Debug.LogError($"- 卡牌 {i} 的 RewardCardView 组件为 null");
                }
            }
            else
            {
                if (rewardCards[i] == null) Debug.LogError($"- 奖励卡牌 {i} 为 null");
                if (rewardCardPrefab == null) Debug.LogError($"- rewardCardPrefab 为 null");
            }
        }

        Debug.Log($"- 总共创建了 {rewardCardViews.Count} 个卡牌视图");
        Debug.Log("=== DisplayRewardCards 结束 ===");
    }

    private void ClearRewardCards()
    {
        // 销毁所有已创建的卡牌UI
        foreach (var cardView in rewardCardViews)
        {
            if (cardView != null && cardView.gameObject != null)
            {
                Destroy(cardView.gameObject);
            }
        }
        rewardCardViews.Clear();
        Debug.Log("清空所有卡牌显示");
    }

    /// <summary>
    /// 检查Slot是否应该被禁用（战斗失败）
    /// </summary>
    public bool ShouldSlotsBeDisabled()
    {
        return !currentResult.isVictory || currentRewardCards.Count == 0;
    }

    /// <summary>
    /// 处理slot点击（由SlotClickHandler调用）
    /// </summary>
    public void OnSlotClicked(int slotIndex)
    {
        Debug.Log($"currentRewardCards.Count = {currentRewardCards.Count}");
        if (slotIndex >= 0 && slotIndex < currentRewardCards.Count)
        {   
            Debug.Log("正在执行 OnSlotClicked");
            // 切换选择状态
            if (currentSelection.selectedCard == currentRewardCards[slotIndex])
            {
                // 取消选择
                currentSelection.selectedCard = null;
                currentSelectedCount = 0;
            }
            else
            {
                // 选择新卡牌
                currentSelection.selectedCard = currentRewardCards[slotIndex];
                currentSelectedCount = 1;
            }

            UpdateCardSelectionVisual();
            UpdateSelectedNumberText();
            UpdateConfirmButtonAndSlotsState();
        }
    }

    /// <summary>
    /// 检查确认按钮是否可以直接点击（战斗失败且没有奖励卡牌）
    /// </summary>
    public bool CanConfirmButtonClickDirectly()
    {
        // 战斗失败时可以直接点击
        if (!currentResult.isVictory)
            return true;

        // 战斗胜利但没有奖励卡牌时可以直接点击
        if (currentResult.isVictory && currentRewardCards.Count == 0)
            return true;

        // 战斗胜利且有奖励卡牌时需要先选择卡牌
        return false;
    }

    /// <summary>
    /// 处理确认按钮点击（由ConfirmButtonClickHandler调用）
    /// </summary>
    public void OnConfirmButtonClicked()
    {
        if (!CanConfirmButtonClickDirectly())
        {
            Debug.Log("正在进行卡牌选择确认");
            if (currentSelectedCount > 0)
            {
                Debug.Log($"确认选择卡牌: {currentSelection.selectedCard?.name}");

                // 通知ResultManager确认选择
                ResultManager resultManager = FindObjectOfType<ResultManager>();
                if (resultManager != null)
                {
                    resultManager.ConfirmRewardSelection(currentSelection);
                }

                // 关闭奖励页面
                if (rewardPage != null) rewardPage.SetActive(false);
                //TODO: 返回地图场景
                SceneManager.LoadScene("MapTest");

                if (battlePage != null) battlePage.SetActive(true); 

                // 清理
                ResetSelection();
            }
            else
            {
                Debug.LogWarning("请先选择一张卡牌");
            }
        }
        else if(currentResult.isVictory)
        {
            // 关闭奖励页面
            if (rewardPage != null) rewardPage.SetActive(false);
            //TODO: 返回地图场景
            SceneManager.LoadScene("MapTest");

            if (battlePage != null) battlePage.SetActive(true);

        }
        else
        {
            Debug.Log("战斗失败，准备返回地图或主菜单...");
            // 关闭奖励页面
            if (rewardPage != null) rewardPage.SetActive(false);
            //TODO: 返回主界面场景
            // 2. [关键] 加载地图场景 (MapTest)
            // 如果您希望失败后直接重新开始新游戏，最好在这里也调用一下 GameManager.Instance.StartNewGame();
            GameManager.Instance.StartNewGame();
            // UnityEngine.SceneManagement.SceneManager.LoadScene("MapTest");

            // 3. [关键] 删除或注释掉这行！不要重新显示战斗页面！
            if (battlePage != null) battlePage.SetActive(true);
        }

    }

    private void UpdateCardSelectionVisual()
    {
        Debug.Log("正在执行 UpdateCardSelectionVisual");
        for (int i = 0; i < rewardCardViews.Count; i++)
        {
            if (i < currentRewardCards.Count && rewardCardViews[i] != null)
            {
                bool isSelected = currentRewardCards[i] == currentSelection.selectedCard;

                // 设置选中效果
                Transform cardTransform = rewardCardViews[i].transform;
                if (isSelected)
                {
                    cardTransform.localScale = Vector3.one * 1.1f; // 放大效果
                    SetCardBorderColor(rewardCardViews[i], Color.yellow);
                }
                else
                {
                    cardTransform.localScale = Vector3.one; // 恢复正常大小
                    SetCardBorderColor(rewardCardViews[i], Color.white);
                }
            }
        }
    }

    private void SetCardBorderColor(RewardCardView cardView, Color color)
    {
        Debug.Log("正在执行 SetCardBorderColor");
        // 如果有边框组件，设置边框颜色
        SpriteRenderer borderRenderer = cardView.GetComponent<SpriteRenderer>();
        if (borderRenderer != null)
        {
            borderRenderer.color = color;
        }
    }

    private void UpdateSelectedNumberText()
    {
        Debug.Log("正在执行 UpdateSelectedNumberText");
        if (selectedNumberText != null)
        {
            if(currentResult.isVictory && currentRewardCards.Count > 0)
            {
                selectedNumberText.text = $"请选择你的奖励（{currentSelectedCount}/{maxSelectedCard}）";
            }
            else if(currentResult.isVictory)
            {
                selectedNumberText.text = "点击“确认”继续游戏";
            }
            else
            {
                selectedNumberText.text = "点击“确认”返回主页";
            }
            
        }
    }

    private void UpdateConfirmButtonVisual()
    {
        Debug.Log("正在执行 UpdateConfirmButtonVisual");

        if (confirmButton != null)
        {
            // 根据是否可以选择来改变按钮外观
            SpriteRenderer buttonRenderer = confirmButton.GetComponent<SpriteRenderer>();
            if (buttonRenderer != null)
            {
                buttonRenderer.color = currentSelectedCount > 0 ? Color.white : Color.gray;
            }
        }
    }

    private void ResetSelection()
    {
        currentSelection = new RewardSelection();
        currentSelectedCount = 0;
        

        UpdateCardSelectionVisual();
        UpdateSelectedNumberText();
        UpdateConfirmButtonAndSlotsState(); 

    }
}